package com.archive.forum.controller;

import com.archive.forum.model.User;
import com.archive.forum.service.UserService;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;



@Controller
public class LoginController {
    @Autowired
    private UserService userService;
    @GetMapping("/login")
    public String login() {
        return "login";
    }
    @PostMapping("/login")
    public String doLogin(@RequestParam(name = "name",required = false) String name,
                          @RequestParam(name = "password",required = false) String password,
                          HttpServletResponse response,
                          Model model) {
        if (name == null || name.isEmpty()|| password == null || password.isEmpty()) {
            model.addAttribute("error", "请填写完整信息");
            return "login";
        }
        User user = new User();
        user.setName(name);
        user.setPassword(userService.sha1(password));
        return userService.login(user,response,model);
    }
    //登出
    @GetMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response){
        request.getSession().removeAttribute("user");
        Cookie cookie = new Cookie("token",null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "redirect:/";
    }

}
